import React, { PureComponent, Fragment } from 'react';
import { Table, Button, Input, message, Popconfirm, Divider } from 'antd';
import styles from './list.less';

export default class TableForm extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            data: props.value,
            loading: false,
            disBtn: false,
        };
    }

    componentWillReceiveProps(nextProps) {
        if ('value' in nextProps) {
            this.setState({
                data: nextProps.value,
                disBtn: false,
            });
        }
    }

    getRowByKey(key, newData) {
        return (newData || this.state.data).filter(item => item.key === key)[0];
    }

    index = 0;
    cacheOriginData = {};
    toggleEditable = (e, key) => {
        e.preventDefault();
        const newData = this.state.data.map(item => ({ ...item }));
        const target = this.getRowByKey(key, newData);
        if (target) {
            // 进入编辑状态时保存原始数据
            if (!target.editable) {
                this.cacheOriginData[key] = { ...target };
            }
            target.editable = !target.editable;
            this.setState({ data: newData, disBtn: true });
        }
    }

    remove(key) {
        const newData = this.state.data.filter(item => item.key !== key);
        this.setState({ data: newData, disBtn: false });
        this.props.onChange(newData);
    }

    newMember = () => {
        this.setState({ disBtn: true });
        const newData = this.state.data.map(item => ({ ...item }));
        newData.push({
            key: this.state.data.length + 1,
            name: '',
            value: '',
            editable: true,
            isNew: true,
        });
        this.index += 1;
        this.setState({ data: newData });
    }

    handleKeyPress(e, key) {
        if (e.key === 'Enter') {
            this.saveRow(e, key);
        }
    }

    handleFieldChange(e, fieldName, key) {
        const newData = this.state.data.map(item => ({ ...item }));
        const target = this.getRowByKey(key, newData);
        if (target) {
            target[fieldName] = e.target.value;
            this.setState({ data: newData });
        }
    }

    saveRow(e, key, val) {
        e.persist();
        this.setState({
            loading: true,
        });
        setTimeout(() => {
            if (this.clickedCancel) {
                this.clickedCancel = false;
                return;
            }
            const target = this.getRowByKey(key) || {};
            if (!target.name || !target.value) {
                message.error('请填写完整成员信息。');
                e.target.focus();
                this.setState({
                    loading: false,
                });
                return;
            }
            delete target.isNew;
            this.toggleEditable(e, key, val);
            this.props.onChange(this.state.data);
            this.setState({
                loading: false,
                disBtn: false,
            });
        }, 500);
    }

    cancel(e, key) {
        this.clickedCancel = true;
        e.preventDefault();
        const newData = this.state.data.map(item => ({ ...item }));
        const target = this.getRowByKey(key, newData);
        if (this.cacheOriginData[key]) {
            Object.assign(target, this.cacheOriginData[key]);
            target.editable = false;
            delete this.cacheOriginData[key];
        } else {
            message.error('属性名已被修改,请点击保存或者还原属性名');
        }
        this.setState({ data: newData, disBtn: false });
        this.clickedCancel = false;
    }

    render() {
        const columns = [{
            title: '属性名',
            dataIndex: 'name',
            width:'40%',
            render: (text, record) => {
                const rText = text.replace(/(^\s*)|(\s*$)/g, '');
                if (record.editable) {
                    return (
                        <Input
                            value={rText}
                            autoFocus
                            onChange={e => this.handleFieldChange(e, 'name', record.key)}
                            onKeyPress={e => this.handleKeyPress(e, record.key)}
                            placeholder="属性名"
                        />
                    );
                }
                return rText;
            },
        }, {
            title: '属性值',
            dataIndex: 'value',
            width:'40%',
            render: (text, record) => {
                if (record.editable) {
                    return (
                        <Input
                            value={text}
                            onChange={e => this.handleFieldChange(e, 'value', record.key)}
                            onKeyPress={e => this.handleKeyPress(e, record.key)}
                            placeholder="属性值"
                        />
                    );
                }
                return text;
            },
        }, {
            title: '操作',
            key: 'action',
            width:'20%',
            render: (text, record) => {
                if (!!record.editable && this.state.loading) {
                    return null;
                }
                if (record.editable) {
                    if (record.isNew) {
                        return (
                            <span>
                                <a onClick={e => this.saveRow(e, record.key, record.value)}>添加</a>
                                <Divider type="vertical" />
                                <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.key)}>
                                    <a>删除</a>
                                </Popconfirm>
                            </span>
                        );
                    }
                    return (
                        <span>
                            <a onClick={e => this.saveRow(e, record.key, record.value)}>保存</a>
                            <Divider type="vertical" />
                            <a onClick={e => this.cancel(e, record.key)}>取消</a>
                        </span>
                    );
                }
                return (
                    <span>
                        <a onClick={e => this.toggleEditable(e, record.key)}>编辑</a>
                        <Divider type="vertical" />
                        <Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.key)}>
                            <a>删除</a>
                        </Popconfirm>
                    </span>
                );
            },
        }];
        return (
            <Fragment>
                <Table
                    loading={this.state.loading}
                    columns={columns}
                    size="small"
                    dataSource={this.state.data}
                    pagination={false}
                    rowClassName={(record) => {
                        return record.editable ? styles.editable : '';
                    }}
                />
                <Button
                    style={{ width: '100%', marginTop: 16, marginBottom: 8 }}
                    type="dashed"
                    onClick={this.newMember}
                    icon="plus"
                    disabled={this.state.disBtn}
                >
                    新增
                </Button>
            </Fragment>
        );
    }
}
